import ffi from 'ffi-napi'
import ref from 'ref-napi'
import iconv from 'iconv-lite';

export default {
  //加载DLL
  init32Dll() {
    console.log('=====init win32 dll=====')
    let proxy_dll = ffi.Library(`${process.env.libPath}/ia32/win32com.dll`, {
      // 'ForceReconnect': ['int', []], 直接传递空数组报错
      "GetIDCardInfo": ['int', ['int', 'string', ref.refType(ref.types.int), 'string', ref.refType(ref.types.int)]],
    })
    return proxy_dll
  },
  readerIDCardInfo(proxy_dll) {
    let readResult = {
      readCode: 0,
      name: '',
      idNo: ''
    }

    let _name = Buffer.alloc(20);
    let _idcode = Buffer.alloc(20);
    let _name_len = ref.alloc(ref.types.int);
    let _idcode_len = ref.alloc(ref.types.int);
    //  let isReaded = true

    readResult.readCode = proxy_dll.GetIDCardInfo(1001, _name, _name_len, _idcode, _idcode_len);
    // 返回读卡接口 -999 返回0能读取到信息  返回 2代表设备链接，但是找不到卡   返回1代表设备没有连接 因为有中文所以要转码
    readResult.name = iconv.decode(_name.slice(0, ref.deref(_name_len) - 1), 'gbk')
    readResult.idNo = iconv.decode(_idcode.slice(0, ref.deref(_idcode_len) - 1), 'gbk')
    return readResult
  },
  /* readerICCardInfo(proxy_dll) {

    // console.log('======返回代码:======'+readCode)
    // console.log('======有效设备端口号:======'+ic_port)

    let readResult = this.readIcCard(0,proxy_dll)
    // if(readResult.readCode === -777 ){
      //如果端口号小于3 且 返回是 -777 尝试下一个端口
      while(readResult.port < 3 && readResult.readCode === -777 ){
        readResult.port += 1
        readResult =  this.readIcCard(readResult.port,proxy_dll)
      }
    // }

    console.log('======返回代码:======'+readResult.readCode)
    console.log('======有效设备端口号:======'+readResult.port)

    return readResult
  }, */
  readerICCardInfo(port,proxy_dll){
    let readResult = {
      readCode: 0,
      cardNo: '', //卡号
      permitNo: '', //许可证
      port: port
    }

    let _cardNo = Buffer.alloc(16) //Buffer
    let _permitNo = Buffer.alloc(16) //Buffer
    let _cardNo_len = ref.alloc(ref.types.int) //ref.types.int
    let _permitNo_len = ref.alloc(ref.types.int) //ref.types.int

    readResult.readCode = proxy_dll.GetICCardInfo(port, _cardNo, _cardNo_len, _permitNo, _permitNo_len)

    readResult.cardNo = _cardNo.slice(0, ref.deref(_cardNo_len)).toString()
    readResult.permitNo = _permitNo.slice(0, ref.deref(_permitNo_len)).toString()
    //如有有中文用这样的方式
    // readResult.name = iconv.decode(_name.slice(0, ref.deref(_name_len) - 1), 'gbk')
    // readResult.idNo = iconv.decode(_idcode.slice(0, ref.deref(_idcode_len) - 1), 'gbk')
    return readResult
  }

}